/*
 * ProtocolSender.cpp
 *
 *  Created on: Sep 8, 2017
 *      Author: guoxs
 */

#include "uart/ProtocolSender.h"
#include "uart/UartContext.h"
#include <stdio.h>

extern BYTE getCheckSum(const BYTE *pData, int len);
bool isSuccessSent;
Mutex rLock;

Response::Response() : uart(UART_TTYS0),DataType(0xD9), len(0), Count(0) {}

Response* Response::getInstance() {
	static Response instance;
	return &instance;
}

void Response::sendData(int DataType, const BYTE *pData, BYTE len) {
	if (isRunning()) {
		requestExit(); //新的数据
	}

	memcpy(this->pData, pData, len);
	this->len = len;
	this->DataType = DataType;

	sendProtocolTo();
	run("response");
}


bool Response::readyToRun(){
	Mutex::Autolock lock(rLock);
	isSuccessSent = false;
	Count = 0;
	return true;
}

bool Response::threadLoop() {
	while (Count <= 3) {
		Count++;
		sleep(100);

		// 检查是否成功接收到ACK/NACK
		{
			Mutex::Autolock lock(rLock);
			if (isSuccessSent || exitPending()) {
				break;
			}
		}
		sendProtocolTo();	//重发
	}

	if (Count > 3) {
		// 超过三次失败，停止发送并进行错误处理
		stop();
	}
	return false; 	//接收正常或重发超量退出线程
}


bool Response::sendProtocolTo() {
	BYTE dataBuf[256];

	dataBuf[0] = CMD_HEAD1;
	dataBuf[1] = DataType;
	dataBuf[2] = len;
	int frameLen = len + 3;
	for (int i = 3,j = 0; i < frameLen; ++i,++j) {
		dataBuf[i] = pData[j];
	}

#ifdef PRO_SUPPORT_CHECK_SUM
	// 校验码
	dataBuf[frameLen] = getCheckSum(dataBuf, frameLen);
	frameLen++;
#endif

	// 发送数据
	return UartContext::sendTo(uart, dataBuf, frameLen);
}

void Response::stop() {
	// 执行停止发送所有数据和相应错误处理的逻辑
	// ...
}

